import 'package:mobx/mobx.dart';
import 'package:hinge/common/index.dart';

part 'chat_list_store.g.dart';

class ChatListStore = _ChatListStore with _$ChatListStore;

abstract class _ChatListStore with Store {
  // 私聊会话列表
  @observable
  ObservableList<ChatSessionModel> privateChats =
      ObservableList<ChatSessionModel>();

  // 群聊会话列表
  @observable
  ObservableList<ChatSessionModel> groupChats =
      ObservableList<ChatSessionModel>();

  // 是否正在加载
  @observable
  bool isLoading = false;

  // 加载聊天列表
  @action
  Future<void> loadChatSessions() async {
    isLoading = true;

    try {
      // 获取所有聊天会话
      final List<ChatSessionModel> allSessions =
          await ChatService.getAllChatSessions();

      // 清空当前列表
      privateChats.clear();
      groupChats.clear();

      // 获取当前用户ID
      final currentUser = UserService.getCurrentUser();
      if (currentUser == null) {
        isLoading = false;
        return;
      }

      // 分类会话
      for (var session in allSessions) {
        // 检查用户是否在会话成员中
        if (session.memberIds.contains(currentUser.id)) {
          if (session.type == ChatSessionType.private) {
            privateChats.add(session);
          } else {
            groupChats.add(session);
          }
        }
      }

      // 根据最新消息时间排序
      _sortSessionsByLatestMessage();
    } catch (e) {
      print('Error loading chat sessions: $e');
    } finally {
      isLoading = false;
    }
  }

  // 根据最新消息时间排序会话
  @action
  Future<void> _sortSessionsByLatestMessage() async {
    try {
      // 获取所有消息
      final allMessages = await ChatService.getAllMessages();

      // 为每个会话查找最新消息时间
      Future<void> sortList(ObservableList<ChatSessionModel> sessions) async {
        // 创建一个会话ID到最新消息时间的映射
        final Map<String, DateTime> latestMessageTimes = {};

        for (var session in sessions) {
          // 查找该会话的所有消息
          final sessionMessages =
              allMessages.where((msg) => msg.chatId == session.id).toList();

          if (sessionMessages.isNotEmpty) {
            // 找出最新消息
            sessionMessages.sort((a, b) => b.createdAt.compareTo(a.createdAt));
            latestMessageTimes[session.id] = sessionMessages.first.createdAt;
          } else {
            // 如果没有消息，使用过去的时间
            latestMessageTimes[session.id] = DateTime(2000);
          }
        }

        // 根据最新消息时间排序
        sessions.sort((a, b) {
          final timeA = latestMessageTimes[a.id] ?? DateTime(2000);
          final timeB = latestMessageTimes[b.id] ?? DateTime(2000);
          return timeB.compareTo(timeA); // 降序排列，最新的在前
        });
      }

      // 对私聊和群聊分别排序
      await sortList(privateChats);
      await sortList(groupChats);
    } catch (e) {
      print('Error sorting sessions: $e');
    }
  }

  // 获取会话的最新消息
  Future<ChatMessageModel?> getLatestMessage(String chatId) async {
    try {
      final messages = await ChatService.getMessagesForChat(chatId);
      if (messages.isEmpty) return null;

      // 按时间降序排序
      messages.sort((a, b) => b.createdAt.compareTo(a.createdAt));
      return messages.first;
    } catch (e) {
      print('Error getting latest message: $e');
      return null;
    }
  }

  // 格式化消息时间
  String formatMessageTime(DateTime dateTime) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final yesterday = today.subtract(const Duration(days: 1));
    final messageDate = DateTime(dateTime.year, dateTime.month, dateTime.day);

    if (messageDate == today) {
      // 今天的消息显示时间
      return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
    } else if (messageDate == yesterday) {
      // 昨天的消息
      return 'Yesterday';
    } else if (now.difference(dateTime).inDays < 7) {
      // 一周内的消息显示星期几
      const weekdays = [
        'Monday',
        'Tuesday',
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday',
        'Sunday',
      ];
      return weekdays[dateTime.weekday - 1];
    } else {
      // 更早的消息显示日期
      return '${dateTime.month}/${dateTime.day}/${dateTime.year}';
    }
  }
}
